import request from '@/utils/request'

// 获取API基础URL，与request.js保持一致
const baseURL = process.env.VUE_APP_BASE_API || '/api'

// 发送聊天消息（流式响应）
export function sendChatMessageStream(data, onMessage, onError, onComplete) {
  const xhr = new XMLHttpRequest()
  
  xhr.open('POST', `${baseURL}/api/ai/chat/send/stream`, true)
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.setRequestHeader('Accept', 'text/event-stream')
  // 允许长连接
  if ('withCredentials' in xhr) {
    xhr.withCredentials = false
  }
  
  // 改进的SSE数据解析，处理数据分割问题
  let lastIndex = 0
  let buffer = ''
  const processChunk = () => {
    const newData = xhr.responseText.substring(lastIndex)
    if (!newData) return
    lastIndex = xhr.responseText.length
    
    // 将新数据添加到缓冲区
    buffer += newData
    
    // 按行分割数据
    const lines = buffer.split('\n')
    
    // 保留最后一行（可能不完整）
    buffer = lines.pop() || ''
    
    // 处理完整的行
    
    for (let line of lines) {
      if (!line.trim()) continue
      line = line.replace(" ", "")
      //console.log('SSE收到数据==============================:', line)
      if (line.startsWith('data:')) {
        const payload = line.substring(5).trim()
        if (payload === '[DONE]') {
          console.log('SSE流完成')
          onComplete && onComplete()
          return
        } else if (payload) {
          try {
            const parsed = JSON.parse(payload)
            if (parsed.error) {
              onError && onError(new Error(parsed.error))
            } else if (parsed.content) {
              //console.log('SSE收到内容:', parsed.content)
              onMessage && onMessage(parsed.content)
            } else if (parsed.conversationId) {
              //console.log('SSE收到会话ID:', parsed.conversationId)
              onMessage && onMessage({ type: 'conversation', conversationId: parsed.conversationId })
            } else if (parsed.conversation_id) {
              //console.log('SSE收到会话ID (conversation_id):', parsed.conversation_id)
              onMessage && onMessage({ type: 'conversation', conversationId: parsed.conversation_id })
            }
          } catch (e) {
            console.log('SSE JSON解析失败:', payload, '错误:', e.message)
          }
        }
      } else if (line.startsWith('{') && line.endsWith('}')) {
        // 处理没有"data: "前缀的JSON行
        try {
          const parsed = JSON.parse(line)
          if (parsed.error) {
            onError && onError(new Error(parsed.error))
          } else if (parsed.content) {
            //console.log('SSE收到内容:', parsed.content)
            onMessage && onMessage(parsed.content)
          } else if (parsed.conversationId) {
            //console.log('SSE收到会话ID:', parsed.conversationId)
            onMessage && onMessage({ type: 'conversation', conversationId: parsed.conversationId })
          } else if (parsed.conversation_id) {
            //console.log('SSE收到会话ID (conversation_id):', parsed.conversation_id)
            onMessage && onMessage({ type: 'conversation', conversationId: parsed.conversation_id })
          }
        } catch (e) {
          console.log('SSE JSON解析失败:', line, '错误:', e.message)
        }
      }
      else{
        console.log('收到数据格式有误'+line)
      }
    }
  }

  xhr.onprogress = processChunk
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 3) {
      //processChunk()
    } else if (xhr.readyState === 4) {
      //processChunk()
      // 当请求完成时，确保触发完成回调
      if (xhr.status === 200) {
        //console.log('SSE请求完成，触发完成回调')
        //onComplete && onComplete()
      }
    }
  }
  
  xhr.onerror = function() {
    //onError && onError(new Error('网络错误'))
  }
  
  xhr.send(JSON.stringify(data))
  
  return {
    abort: () => xhr.abort()
  }
}

// 获取会话列表
export function getConversations(userId) {
  return request({
    url: '/api/ai/chat/conversations',
    method: 'get',
    params: { userId }
  })
}

// 获取会话消息历史
export function getConversationMessages(conversationId) {
  return request({
    url: `/api/ai/chat/conversations/${conversationId}/messages`,
    method: 'get'
  })
}

// 归档会话
export function archiveConversation(conversationId) {
  return request({
    url: `/api/ai/chat/conversations/${conversationId}/archive`,
    method: 'post'
  })
}

// 上传文件
export function uploadFile(file, userId) {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('userId', userId)
  
  return request({
    url: '/api/ai/chat/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取用户文件列表
export function getUserFiles(userId) {
  return request({
    url: '/api/ai/chat/files',
    method: 'get',
    params: { userId }
  })
}

// 删除文件
export function deleteFile(fileId) {
  return request({
    url: `/api/ai/chat/files/${fileId}`,
    method: 'delete'
  })
}
